<template>
	<view class="load" v-if="!load">
		<u-loading-icon mode="circle" inactive-color="#fff" text="正在加载..." vertical></u-loading-icon>
	</view>
	<view v-else style="overflow: hidden;height: 100vh;">

		<view class="tap">
			<view class="tabs wap" v-if="typeindex == 0 || typeindex == 1 || typeindex == 2">
				<view class="tabs_item " :class="{ 'tabs_item_curr': tabInd == index }" @click="setTab(index)"
					v-for="(item, index) in tabList" :key="index">
					{{ item }}
				</view>
			</view>
			<view class="tabs wap" v-if="typeindex == 3">
				<view v-for="(item, index) in typelist" :key="index">
					<view class="tabs_item " :class="{ 'tabs_item_curr': item.value == fieldInd }"
						@click="setfield(item.value)">
						{{ item.lable }}
					</view>
				</view>

			</view>
		</view>
		<x-scroll :fixed="true" :isNav="false" @scroll="scroll" :offset="0" @onRefresh="onRefresh"
			@scrolltolower="scrolltolower" :refresh="freshing">
			<!-- 我发起的 -->
			<view class="ball" v-if="(typeindex == 0 || typeindex == 1 || typeindex == 2)">
				<view class="ball_list" v-if="Array.isArray(MyApplyList.list) && MyApplyList.list.length > 0">
					<block v-for="(item) in MyApplyList.list" :key="item.ID">
						<view class="listbox" @click.stop="nav_to('/pages/ball/ball_details?id=' + item.ID)">
							<!-- <view class="status">
								{{'待使用'}}
							</view> -->
							<view class="contentbox">
								<image class="imgleft" :src="item.Images.split(',')[0]" mode="aspectFill"></image>
								<view class="rightbox">
									<view>
										<view class="nametext">{{ $util.entitiesToUtf16(item.Title) }}</view>
										<view class="infobox">
											<image class="infoimg"
												src="https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17229991748171392.png">
											</image>
											<view class="infotext">{{ getTime2(item.ServerDate) + ' '+getWeek(item.ServerDate)+item.ServerTime}}</view>
										</view>
										<view class="infobox">
											<image class="infoimg"
												src="https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17229991973631170.png">
											</image>
											<view class="infotext hiddenText">{{ item.Place }}</view>
										</view>
									</view>
									<view class="pricebox">
										<block v-if="item.Status != -99">
										<view class="pricebtn" @click.stop="nav_to('/pages/together/ple_order?id='+item.ID)">{{'核销列表'}}</view>
										<view class="pricebtn" @click.stop="checkEQ(item.ID)">核销</view>
										</block>
										<block v-else>
											<view class="review">审核中</view>
										</block>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>
				<block v-else>
					<u-empty mode="list" width="100" height="100"
						icon="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17124806786111367.png" :show="true"
						iconSize="32" text="暂无活动"></u-empty>

				</block>
				<view style="height: 200rpx;"></view>
			</view>
			<!-- 订场管理 -->
			<view class="ball" v-if="typeindex == 3">
				<view class="ball_list wap" v-if="Array.isArray(MyRegisterList.list) && MyRegisterList.list.length > 0">
					<view class="item" :class="{ 'shadow': item.Status == 1, 'shadow': item.Status == -1 }"
						v-for="(item, index) in MyRegisterList.list" :key="index"
						@click="nav_to('/pages/ball/venue_detail?id=' + item.ID)">
						<view class="namebox">
							<view class="placename">{{ item.ShopName }}</view>
							<view
								:class="{ 'placestate': item.Status == 0, 'complete': item.Status == 1, 'complete': item.Status == -1 }">
								{{ getBallStatusStr(item) }}</view>
						</view>
						<view class="placetype">{{ item.SortType || '' }}</view>
						<view class="placetime">
							<view class="time">{{ item.OrderDate ? getTime3(item.OrderDate) : '' }}</view>
							<view class="placesum">1个场次</view>
						</view>
					</view>
				</view>
				<block v-else>
					<u-empty mode="list" width="100" height="100"
						icon="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17124806786111367.png" :show="true"
						iconSize="32" text="无订场"></u-empty>

				</block>
				<view style="height: 200rpx;"></view>
			</view>
			<!-- 商家订场管理 -->
			<view class="ball" v-if="typeindex == 4">
				<view class="ball_list wap" v-if="Array.isArray(MyShopList.list) && MyShopList.list.length > 0">
					<view class="item" :class="{ 'shadow': item.Status == 1, 'shadow': item.Status == -1 }"
						v-for="(item, index) in MyShopList.list" :key="index"
						@click="nav_to('/pages/ball/venue_detail?id=' + item.ID + '&type=1')">
						<view class="namebox">
							<view class="placename">{{ item.ShopName }}</view>
							<view
								:class="{ 'placestate': item.Status == 0, 'complete': item.Status == 1, 'complete': item.Status == -1 }">
								{{ getBallStatusStr(item) }}</view>
						</view>
						<view class="placetype">{{ item.SortType || '' }}</view>
						<view class="placetime">
							<view class="time">{{ item.OrderDate ? getTime3(item.OrderDate) : '' }}</view>
							<view class="placesum">1个场次</view>
						</view>
					</view>
				</view>
				<block v-else>
					<u-empty mode="list" width="100" height="100"
						icon="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/17124806786111367.png" :show="true"
						iconSize="32" text="无订场"></u-empty>

				</block>
				<view style="height: 200rpx;"></view>
			</view>
		</x-scroll>

		<uni-popup type="center" ref="checkbox">
			<view class="Successbox">
				<image class="suimg" src="https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1723017497812406.png"></image>
				<view class="sutext">核销成功！</view>
				<view class="coutbtn" @click="suopenclose">继续核销</view>
				<view class="suclose" @click="suclose">关闭</view>
			</view>
		</uni-popup>
		<uni-popup type="center" ref="Failcheckbox">
			<view class="Successbox">
				<image class="suimg" src="https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17230184678361039.png"></image>
				<view class="sutext">核销失败</view>
				<view class="sutfiext">{{mesAge?mesAge:''}}</view>
				<view class="coutbtn" @click="Fiopenclose">继续核销</view>
				<view class="suclose" @click="Ficlose">关闭</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import imgbox from "@/pages/ball/components/imgbox/imgbox.vue";
import topStatus from "@/components/topStatus/topStatus.vue";
import huiCell from "./components/huiCell/huiCell.vue";
import actCell from "./components/actCell/actCell.vue";
export default {
	tabTop: 0,
	components: {
		imgbox,
		topStatus,
		huiCell,
		actCell
	},
	data() {
		return {
			mesAge:'',
			isStatus: 99,
			tabList: ['全部', '未开始', '进行中', '已结束'],
			applyList: [],
			typelist: [
				{
					lable: '全部',
					value: 0
				},
				{
					lable: '待开始',
					value: 1
				}, {
					lable: '已完成',
					value: 2
				}, {
					lable: '已取消',
					value: 3
				},
			],
			fieldInd: 0,
			typeindex: 0,
			BarTitle: '',
			privatelist: [], // 私人球局列表
			ossPath: null,
			IsExpiredUser: {

			},
			IsTrueName: false,
			userNums: {},
			freshing: true,
			load: false,
			ballTab: 0,
			user: {},
			tabInd: 0,
			showTop: false,

			// 我发起的组局
			MyApplyList: {
				list: [],
				PageIndex: 1,
				PageSize: 15
			},
			// 我报名的组局
			MyTakeList: {
				list: [],
				PageIndex: 1,
				PageSize: 15
			},
			//我的订场
			MyRegisterList: {
				list: [],
				PageIndex: 1,
				PageSize: 15,
			},
			//商家订场管理
			MyShopList: {
				list: [],
				PageIndex: 1,
				PageSize: 15,
			},
			shopid: '',
			ossWatermark: '',
			checkeqId:0,
		}
	},
	computed: {
		//我预约的
		getBallyuyue() {
			return obj => {
				let str = "";
				if (obj.Status == 0) {
					str = "预约中";

				} else if (obj.Status == 1) {
					str = "预约成功";
				} else if (obj.Status == 2) {
					str = "已发奖励"
				} else if (obj.Status == 3) {
					str = "已结束"
				} else if (obj.Status == -1) {
					str = "已拒绝"
				}

				return str;
			}
		},
		getUserType(l) {
			return l => {
				if (l.indexOf('年') != -1) {
					return 2
				} else if (l.indexOf('金') != -1) {
					return 1
				} else {
					return 0
				}
			}
		},
		getTime2() {
			return l => {
				let d = new Date(l);
				let timestamp = d.getTime();
				return this.$u.date(timestamp, 'mm-dd');
			}
		},
		getTime3() {
			return l => {
				let d = new Date(l);
				let timestamp = d.getTime();
				return this.$u.date(timestamp, 'yyyy-mm-dd');
			}
		},
	},
	onLoad(e) {
		if (e.tab) {
			this.tabInd = e.tab;
		}
		this.getLogo()
		this.typeindex = e.index
		// this.BarTitle = e.title
		this.shopid = e.shopId
		if(e.title){
			uni.setNavigationBarTitle({
				title: e.title,
				success: function () {
				},
				fail: function (err) {
				}
			});
		}else{
			uni.setNavigationBarTitle({
				title: '我的活动',
				success: function () {
				},
				fail: function (err) {
				}
			});
		}
		
		this.init();
	},
	onReady() {

	},
	onShow() {
		this.init();
		this.getUserInfo();
		this.ossPath = this.$ossPath
	},

	methods: {
		Fiopenclose(){
			this.$refs['Failcheckbox'].close()
			this.checkEQ()
		},
		suopenclose(){
			this.$refs['checkbox'].close()
			this.checkEQ()
		},
		Ficlose(){
			this.$refs['Failcheckbox'].close()
		},
		suclose(){
			this.$refs['checkbox'].close()
		},
		getLogo() {
			this.ossWatermark = this.$ossWatermark
		},
		//过滤标签
		repdis(msg) {
			var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
			msg = msg.replace(/[|]*\n/, ''); //去除行尾空格
			msg = msg.replace(/&npsp;/gi, ''); //去掉npsp
			return msg;
		},
		// 我发起的组局状态
		getBallStatusStr(item) {
			let str = ''
			if (item.Status == 0) {
				str = "待开始";
			} else if (item.Status == 1) {
				str = "已完成";
			} else if (item.Status == -1) {
				str = "已取消"
			}
			return str;
		},
		setBg() {
			let _this = this;
			uni.chooseMedia({
				count: 1, //默认9
				mediaType: ['image'],
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: async function (res) {
					let r = await _this.uploading(res.tempFiles[0].tempFilePath);
					let b = await _this.$api.post('User/UpdateUserBG', { BgImg: r, userID: _this.user.UserID });
					setTimeout(async () => {
						await _this.getUserInfo();
					}, 500)

				}
			})
		},

		// 文件上传
		async uploading(url, tempKey) {
			if (tempKey) {
				let r = await this.$api.upload(
					"/Community/Upload", {
					path: url,
				},
					(pro) => {
						this.localList.forEach((item) => {
							if (item.tempKey == tempKey) {
								item.pro = pro;
							}
						});
					}
				);
				this.localList.forEach((item) => {
					if (item.tempKey == tempKey) {
						item.netPath = r;
					}
				});

			} else {
				let _this = this;
				let r = await this.$api.upload('/Community/Upload', {
					path: url
				}, pro => {
					if (pro != 100) {
						_this.$pv.load('已上传' + pro + '%')
					} else {
						_this.$pv.closeLoad();
					}


					// this.localList.forEach(item => {
					//     if(item.tempKey == tempKey){
					//         item.pro = pro;
					//     }
					// })
				});
				return r;
			}

		},

		// 切换
		setfield(e) {
			this.fieldInd = e;
			this.MyRegisterList = {
				list: [],
				PageIndex: 1,
				PageSize: 15
			}
			this.getMyRegister();
		},
		setTab(e) {
			this.tabInd = e;
			this.MyApplyList.PageIndex = 1
			if(e == 0){
				this.isStatus = 99
				this.getMyApply()
			}else if(e == 1){
				this.isStatus = 0
				this.getMyApply()
			}else if(e == 2){
				this.isStatus = 1
				this.getMyApply()
			}else if(e == 3){
				this.isStatus = 3
				this.getMyApply()
			}
		},
		// 滚动
		scroll(e) {
			let top = e.detail.scrollTop;
			if (top > (this.tabTop - 44)) {
				this.showTop = true;
			} else {
				this.showTop = false;
			}
		},
		//下拉刷新
		async onRefresh() {
			this.getUserInfo();

			if (this.tabInd == 0 && (this.typeindex == 0 || this.typeindex == 1 || this.typeindex == 2)) {
				this.MyApplyList.PageIndex = 1;
				this.MyApplyList.PageSize = 15;
				await this.getMyApply();

			} else if (this.tabInd == 1 && (this.typeindex == 0 || this.typeindex == 1 || this.typeindex == 2)) {
				this.MyTakeList.PageIndex = 1;
				this.MyTakeList.PageSize = 15;
				await this.getMyTake();
			} else if (this.typeindex == 3) {
				this.MyRegisterList.PageIndex = 1;
				this.MyRegisterList.PageSize = 15;
				await this.getMyRegister();
			} else if (this.typeindex == 4) {
				this.MyShopList.PageIndex = 1;
				this.MyShopList.PageSize = 15;
				await this.getMyShopList();
			}
			uni.$emit('triggered');
		},
		//滚动到底部触发
		async scrolltolower() {
			// 确定是哪一个tab 
			if ((this.typeindex == 0 || this.typeindex == 1 || this.typeindex == 2)) {
				this.MyApplyList.PageIndex++
				await this.getMyApply();

			} else if (this.typeindex == 3) {
				this.MyRegisterList.PageIndex++
				await this.getMyRegister();
			} else if (this.typeindex == 4) {
				this.MyShopList.PageIndex++
				await this.getMyShopList();
			}
		},
		// ball_details_prebook
		toMyrPrebook(item) {
			this.nav_to(`/pages/ball/reserva_details?id=${item.ID}`);
		},
		toMyAttend(item) {
			this.nav_to(`/pages/ball/ball_details?id=${item.ID}`);
		},
		toDetails(item) {
			if (item.AppointmentType == '私人球局') {
				this.nav_to(`/pages/ball/reserva_details?id=${item.ID}`)
			} else {
				this.nav_to(`/pages/ball/ball_details?id=${item.ID}`);
			}
		},
		// 去重,后面的覆盖前面的
		clearRepetition(arr, key = "id") {
			let newArr = [];
			arr.forEach(item => {
				let index;
				let check = newArr.every((newItem, i) => {
					if (item[key] !== newItem[key]) {
						index = -1;
						return true;
					} else {
						index = i;

						return false;
					}
				})
				if (check) {
					newArr.push(item);
				} else {
					newArr.splice(index, 1, item);
				}

			})
			return newArr;
		},
		async getMyApply() {
			let Appointment = ['一起挥', '招学员', '找私教']
			let res = await this.$api.post('Appointment/MyApply', {
				PageIndex: this.MyApplyList.PageIndex,
				PageSize: this.MyApplyList.PageSize,
				AppointmentType: Appointment[this.typeindex],
				Status: this.isStatus,
			});
			let list = this.MyApplyList.PageIndex==1?res.data:this.MyApplyList.list.concat(res.data);
			// this.MyApplyList.list = list
			// this.MyApplyList.list = this.MyApplyList.list.concat(this.MyApplyList.list)
			this.MyApplyList.list = this.clearRepetition(list, "ID");
			
			
			console.log(this.typeindex);
			console.log(this.MyApplyList.list);
			//报名列表
			// this.applyList = this.MyApplyList.list.filter((v) => v.Status != -1 && v.Status != -2).map((v) => {
			// 	return v;
			// });
			// console.log(this.applyList);
			// this.privatelist = this.MyApplyList.list.filter((item) => {
			// 	return item.AppointmentType == '私人球局'
			// })
		},
		async getMyTake() {
			let Appointment = ['一起挥', '招学员', '找私教']
			let res = await this.$api.post('Appointment/MyTake', {
				PageIndex: this.MyTakeList.PageIndex,
				PageSize: this.MyTakeList.PageSize,
				AppointmentType: Appointment[this.typeindex]
			});
			if (!res.data) return
			let list = this.MyTakeList.list.concat(res.data)
			this.MyTakeList.list = this.clearRepetition(list, "ID");
		},
		async getMyRegister() {
			let Status = ['99', '0', '1', '3']
			let res = await this.$api.post('ShopOrder/MyOrders', {
				PageIndex: this.MyRegisterList.PageIndex,
				PageSize: this.MyRegisterList.PageSize,
				Status: Status[this.fieldInd]
			});
			if (!res.data) return
			let list = this.MyRegisterList.list.concat(res.data)
			this.MyRegisterList.list = this.clearRepetition(list, "ID");

		},
		async getMyShopList() {
			let Status = ['99', '0', '1', '-1']
			let res = await this.$api.post('ShopOrder/MyShopOrders', {
				ShopID: this.shopid,
				PageIndex: this.MyRegisterList.PageIndex,
				PageSize: this.MyRegisterList.PageSize,
			});
			if (!res.data) return
			let list = this.MyShopList.list.concat(res.data)
			this.MyShopList.list = this.clearRepetition(list, "ID");

		},
		// async getIsExpiredUser() {
		// 	let res = await this.$api.post('User/IsExpiredUser');
		// 	this.IsExpiredUser = res.data;
		// },

		lookImg(index) {

			let list = this.myImgList.map(item => item.Images);
			uni.previewImage({
				urls: list,
				current: index
			})
		},
		async init() {
			let _this = this;
			await this.getUserInfo();
			await this.getSaleChannelDetail();
			await this.getIsTrueName();
			// await this.getIsExpiredUser();

			if (this.typeindex == 0 || this.typeindex == 1 || this.typeindex == 2) {
				await this.getMyApply();
			} else if (this.typeindex == 3) {
				await this.getMyRegister();
			} else if (this.typeindex == 4) {
				await this.getMyShopList()
			}
			this.load = true;


		},
		async getSaleChannelDetail() {
			let res = await this.$api.post('/SaleChannel/SaleChannelDetail', { CompanyID: 6002 });
			this.userNums = res.data;
		},
		async getUserInfo() {
			let u = uni.getStorageSync('user');
			let res = await this.$api.post('User/GetUserInfo', { ID: u.UserID });
			this.user = res.data;
		},

		async getIsTrueName() {
			let res = await this.$api.post('User/IsTrueName')
			this.IsTrueName = res.data;
		},
		// 点击核销
		checkEQ(e=0) {
			let that = this
			if (e != 0) {
				that.checkeqId = e
			}
			uni.scanCode({
				scanType:['qrCode'],
				success: async function (res) {
					let res1 = await that.$api.post('/Appointment/Verified', { 
						ActionCode: res.result,
						AppointmentID:that.checkeqId 
					});
					if (res1.code == 0) {
						that.$refs['checkbox'].open()
					}else{
						that.mesAge = res1.message
						that.$refs['Failcheckbox'].open()
					}
					// that.$pv.msg(res1.message);
				}
			});
		},

	},

}
</script>

<style lang="scss">
page {
	background-color: #F6F6F6;
}

.nav {
	height: 44px;
	line-height: 44px;
	text-align: center;
}

.tabs {
	// position: sticky;
	// top: 0;
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: space-around;
	background: #fff;
	transition: 0.3 all;

	.tabs_item {
		height: 100rpx;
		line-height: 100rpx;
		padding-left: 12rpx;
		padding-right: 12rpx;
		color: #999999;
	}

	.tabs_item_curr {
		color: #333333;
		font-weight: bolder;
		position: relative;

		&::before {
			display: block;
			content: "";
			position: absolute;
			left: 50%;
			bottom: 0;
			transform: translateX(-50%);
			width: 48rpx;
			height: 8rpx;
			border-radius: 5rpx;
			background: #000000;
		}
	}
}

.ball_list {
	margin-top: 20rpx;

	.item {
		margin-top: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		padding: 32rpx 24rpx;
	}

	.shadow {
		background-color: rgba(211, 211, 211, 0.6);
	}
}

.ball {
	padding-bottom: 30rpx;
}

.ball_list {
	margin-top: 20rpx;
	padding: 0 24rpx;
	width: 100%;

}

.namebox {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;

	.placename {
		font-size: 36rpx;
		color: #333333;
		font-weight: 600;
	}

	.placestate {
		font-weight: 500;
		font-size: 28rpx;
		color: #2BA139;
	}

	.complete {
		font-weight: 500;
		font-size: 28rpx;
		color: #999999;
	}
}

.placetype {
	color: #333333;
	font-size: 28rpx;
	font-weight: 500;
	margin-bottom: 12rpx;
}

.placetime {
	display: flex;
	align-items: center;
	justify-content: space-between;

	.time {
		font-size: 28rpx;
		color: #333333;
	}

	.placesum {
		font-size: 28rpx;
		color: #333333;
	}
}

.listbox {
	width: 686rpx;
	margin: 24rpx auto;
	padding: 24rpx;
	background-color: #fff;
	border-radius: 16rpx;

	.status {
		font-size: 28rpx;
		color: #333333;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #e4e4e4;
	}

	.contentbox {
		display: flex;
		margin-top: 30rpx;

		.imgleft {
			width: 176rpx;
			height: 232rpx;
			border-radius: 8rpx;
			margin-right: 32rpx;
			background-color: #000000;
		}

		.rightbox {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.nametext {
				font-size: 28rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 32rpx;
			}

			.infobox {
				display: flex;
				align-items: center;

				.infoimg {
					width: 32rpx;
					height: 34rpx;
					margin-right: 4rpx;
				}

				.infotext {
					width: 350rpx;
					font-size: 24rpx;
					color: #999999;
				}
			}

			.pricebox {
				display: flex;
				align-items: center;
				justify-content: flex-end;

				.pricebtn {
					width: 112rpx;
					height: 56rpx;
					border-radius: 28rpx;
					border: 2rpx solid #000000;
					color: #000000;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-left: 54rpx;
				}
				.review{
					width: 112rpx;
					height: 56rpx;
					border-radius: 28rpx;
					border: 2rpx solid #e4e4e4;
					color: #999999;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					// margin-left: 54rpx;
				}
				.pricetext {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
				}

				.sum {
					font-size: 32rpx;
					color: #333333;
				}
			}
		}
	}
}
.Successbox{
	width: 544rpx;
	background: #FFFFFF;
	border-radius: 48rpx;
	text-align: center;
    padding: 56rpx;
	.suimg{
		width: 152rpx;
		height: 152rpx;
	}
	.sutext{
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-top: 48rpx;
		margin-bottom: 40rpx;
	}
	.sutfiext{
		font-size: 28rpx;
		color: #999999;
		margin-bottom: 56rpx;
	}
	.coutbtn{
		width: 440rpx;
		height: 88rpx;
		background: #000000;
		border-radius: 44rpx;
		font-size: 28rpx;
		font-weight: bold;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.suclose{
		font-size: 28rpx;
		color: #999999;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
	}
}
</style>